﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WebGetter
{
    class TianYaRule : IWebGetRule
    {
        private const string ItemNo = "ItemNo";

        private const string MATCHPATTERN = @"http://www\.tianya\.cn/techforum/content/.+";
        private const string GET_CURRENT_URL_FORMAT = @"http://www.tianya.cn/techforum/content/{0}/{1}/{2}.shtml";
        public void InitHelper(RegexHelper helper)
        {
            helper.GetByRegexp(Keys.Title, @"<title>(?<val>.+?)</title>");
            helper.GetByRegexp(Keys.PageNo, @"(<em\sclass=.current.>(?<val>\d+)</em>)|(intpage_num\s=\s'(?<val>\d+)';)");
            helper.GetByRegexp(Keys.TotalNo, @"<span>共(?<val>\d+)页</span>");
            helper.GetByRegexp(Keys.NextUrl, @"<a\shref=['""]?(?<val>[^>]+?)['""]?\s?>下一页</a>");
            helper.GetByRegexp(Keys.PageAuthor, @"chrAuthorName\s=\s.(?<val>.+?).;");
            helper.GetByRegexp(Keys.Author, @"<a\shref=.?http://my.tianya.cn/\d+.?\starget=.?_blank.?>(?<val>.+?)</a>");

            helper.GetByRegexp(Keys.Content, @"<div\sclass=['""]post['""][^>]+?>(?<val>.*?)(</div>|<span)");
            helper.GetByRegexp(Keys.Floor, @"<span\sclass=.floor.>(?<val>.+?)(<sup>|</span>)");
            helper.GetByRegexp(Keys.PostTime, @"日期：(?<val>\d{4}-\d{1,2}-\d{1,2}(\s+\d{1,2}(:\d{1,2}){1,2})?)</div>");

            helper.GetByRegexp(ItemNo, @"var\sitemId\s=\s.(?<val>.+?).;");
            helper.GetByRegexp(Keys.ArticleId, @"var\sarticleId\s=\s.(?<val>.+?).;");
            helper.GetByRegexp(Keys.PageUrl, @"strPageUrl\s*=\s*(""|')(?<val>.+?)(""|')(;|//).");
        }

        public string GetCurrentUrl(RegexHelper helper)
        {
            return string.Format(GET_CURRENT_URL_FORMAT,
                helper.GetKeyItem(ItemNo),
                helper.GetKeyItem(Keys.PageNo),
                helper.GetKeyItem(Keys.ArticleId));
        }

        public bool IsMatched(string url)
        {
            return Regex.IsMatch(url, MATCHPATTERN);
        }
    }
}
